package xuanzhen.christian.controller;

import java.text.ParsePosition;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang.RandomStringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import xuanzhen.christian.pojo.ChrisCus;
import xuanzhen.christian.service.ChrisService;
import xuanzhen.dating.pojo.DatingUser;
import xuanzhen.dating.service.DatingService;
import xuanzhen.dating.service.SeeShareService;
import xuanzhen.wx.pojo.AccessToken;
import xuanzhen.wx.pojo.Jsticket;
import xuanzhen.wx.pojo.WxUserMsg;
import xuanzhen.wx.service.CoreService;
import xuanzhen.wx.util.EmojiFilter;
import xuanzhen.wx.util.fina.WxSet;

@Controller
@RequestMapping("/christian")
public class ChrisController {
	@Resource
	CoreService coreService;
	@Resource
	DatingService datingService;
	@Resource
	ChrisService chrisService;
	@RequestMapping(value = "/index.html", method = RequestMethod.GET)
	public String index(Model model, HttpSession session, HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		
		
		
		String tag ="";
		tag =  request.getParameter("spread");
		session.setAttribute("spread", tag);
		System.out.println(tag);
		//createTime
		Date now = new Date();
		SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");// 可以方便地修改日期格式
		String nowTime = dateFormat.format(now);
		ParsePosition pos = new ParsePosition(0);
		Date currentTime_2 = dateFormat.parse(nowTime, pos);
		// 获取用户微信信息
		ChrisCus umsg = new ChrisCus();
		umsg.setCreateTime(currentTime_2);
		umsg.setState(2);
		umsg.setSpread(tag);
		umsg.setNickname("dadadaad");
		String nk= EmojiFilter.filterEmoji(umsg.getNickname());
		umsg.setNickname(nk); 
		chrisService.insertCus(umsg);
		ChrisCus backMsg = chrisService.queryListByCus(umsg).get(0);
		model.addAttribute("backMsgId", backMsg.getId());
		/*String tag =  request.getParameter("spread");
		session.setAttribute("spread", tag);
		
		seeService.addweShare(tag);
			String spread =  request.getParameter("spread");
			model.addAttribute("spread", spread);*/
		return "chris/chrisForm";
	}
	@RequestMapping(value = "/index1.html", method = RequestMethod.GET)
	public String indexfo(Model model, HttpSession session, HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		/*String tag =  request.getParameter("spread");
		session.setAttribute("spread", tag);
		
		seeService.addweShare(tag);
			String spread =  request.getParameter("spread");
			model.addAttribute("spread", spread);*/
		return "chris/chrisIndex";
	}
	/**
	 * 跳转授权
	 * @param model
	 * @param session
	 * @param request
	 * @param response
	 * @throws Exception
	 */
	@RequestMapping(value = "/regist.html", method = RequestMethod.GET)
	public void toRight(Model model, HttpSession session, HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		String tag =  request.getParameter("spread");
		session.setAttribute("spread", tag);
		
			response.sendRedirect(coreService.getChrisRight());
		
	}
	/**
	 * 获取授权
	 */
	@RequestMapping(value = "/getRight.html", method = RequestMethod.GET)
	public String getRight(Model model, HttpSession session, HttpServletRequest request) throws Exception {
		
		// 获取授权后code
		String code = request.getParameter("code");
		session.setAttribute("code", code);
		String state = request.getParameter("state");
		// 获取token
		String ua = request.getHeader("user-agent").toLowerCase();
		if(ua.indexOf("micromessenger")>0){
			AccessToken token = coreService.getAccessToken(code, state);
			System.out.println(token);
					String tag ="";
					if(request.getSession().getAttribute("spread")==null){
						tag ="noSpread";
					}else{
						tag =  request.getSession().getAttribute("spread").toString();
					}
					
					System.out.println(tag);
					//createTime
					Date now = new Date();
					SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");// 可以方便地修改日期格式
					String nowTime = dateFormat.format(now);
					ParsePosition pos = new ParsePosition(0);
					Date currentTime_2 = dateFormat.parse(nowTime, pos);
					// 获取用户微信信息
					if(token.getToken()!=null){
						ChrisCus umsg = chrisService.catchUserMsg(token);
						umsg.setCreateTime(currentTime_2);
						umsg.setState(2);
						umsg.setSpread(tag);
						String nk= EmojiFilter.filterEmoji(umsg.getNickname());
						umsg.setNickname(nk); 
						chrisService.insertCus(umsg);
						
						ChrisCus backMsg = chrisService.queryListByCus(umsg).get(0);
						model.addAttribute("backMsgId", backMsg.getId());
					}
		}
		
				
		// 获得js票
				AccessToken tokenCe = coreService.getAccessTokenC();
				Jsticket ticket = coreService.getJsticket(tokenCe);
				session.setAttribute("ticket", ticket);
				System.out.println(ticket);
				// 获取时间戳
				long timestamp = System.currentTimeMillis() / 1000;
				session.setAttribute("timestamp", timestamp);
				// 生成随机字符串
				String noncestr = RandomStringUtils.randomAlphanumeric(16);
				session.setAttribute("noncestr", noncestr);
				
				// appid
				session.setAttribute("appid", WxSet.APPID);
				// 当前网页url
				String url = request.getScheme() + "://" + request.getServerName() + request.getContextPath()+"/christian/index.html?spread="+session.getAttribute("spread");
//				url = request.getScheme() + "://" + request.getServerName() + request.getRequestURI();
//				if (request.getQueryString() != null) {
//					url += "?" + request.getQueryString();
//				} 		
				System.out.println(url);
					/*	"http://run.xuanzhen-tech.com/wx_project/user/getRight.html?code=" + code + "&state=STATE";*/
				// 签名
				String signature = coreService.getSignature(url, timestamp + "", noncestr, ticket.getTicket());
				session.setAttribute("signature", signature);

		return "chris/redirect";
	}
	@RequestMapping(value = "/signIn.html", method={RequestMethod.GET,RequestMethod.POST})
	public String add(Model model, HttpSession session,String cusPhone,String bid, HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		// 获得js票
		AccessToken tokenCe = coreService.getAccessTokenC();
		Jsticket ticket = coreService.getJsticket(tokenCe);
		session.setAttribute("ticket", ticket);
		System.out.println(ticket);
		// 获取时间戳
		long timestamp = System.currentTimeMillis() / 1000;
		session.setAttribute("timestamp", timestamp);
		// 生成随机字符串
		String noncestr = RandomStringUtils.randomAlphanumeric(16);
		session.setAttribute("noncestr", noncestr);
		
		// appid
		session.setAttribute("appid", WxSet.APPID);
		// 当前网页url
		String url = "";
		url = request.getScheme() + "://" + request.getServerName() + request.getRequestURI();
		if (request.getQueryString() != null) {
			url += "?" + request.getQueryString();
		} 		
		System.out.println(url);
			/*	"http://run.xuanzhen-tech.com/wx_project/user/getRight.html?code=" + code + "&state=STATE";*/
		// 签名
		String signature = coreService.getSignature(url, timestamp + "", noncestr, ticket.getTicket());
		session.setAttribute("signature", signature);
		
		//存储id查询
		ChrisCus chrisCus = new ChrisCus();
		if(cusPhone !=null & bid !=null){
		
		int cid = Integer.parseInt(bid);
		chrisCus.setId(cid);
		chrisCus.setCusphone(null);
		System.out.println(cid);
		chrisCus = chrisService.queryListByCus(chrisCus).get(0);
		//存储手机
		chrisCus.setCusphone(cusPhone);
		chrisService.updateCus(chrisCus);
		}else{
			//createTime
			Date now = new Date();
			SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");// 可以方便地修改日期格式
			String nowTime = dateFormat.format(now);
			ParsePosition pos = new ParsePosition(0);
			Date currentTime_2 = dateFormat.parse(nowTime, pos);
			chrisCus.setCreateTime(currentTime_2);
			chrisCus.setCusphone(cusPhone);
			chrisCus.setState(1);
			chrisService.insertCus(chrisCus);
		}
		return "chris/chrisIndex";
	}
	
	@RequestMapping(value = "/register.html", method={RequestMethod.GET,RequestMethod.POST})
	public String register(){
		return "chris/register";
	}
	
}
